#include <asm-generic/errno-base.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc,char* argv[]){
  key_t key = ftok(".",1);
  if(key < 0){
    perror("ftok fail");
    exit(-1);
  }

  int shm_id = shmget(key,1024,IPC_CREAT | IPC_EXCL | 0666);
  if(shm_id < 0 && errno == EEXIST){
    shm_id = shmget(key,1024,0666);
  }else{
    perror("ftok fail");
    exit(-1);
  }

  char* shm_buf = shmat(shm_id,NULL,0);
  if(shm_buf == (void*)-1){
    perror("shmget fail");
    exit(-1);
  }

  sem_t* sem[2];
  sem[0] = sem_open("a",O_CREAT,0666,1);
  sem[1] = sem_open("b",O_CREAT,0666,1);

  while(1){
    sem_wait(sem[1]);
    printf("read is %s\n",shm_buf);
    sem_post(sem[0]);
    if(!strcmp("bye",shm_buf))
      break;
  }

  shmdt(shm_buf);
  shmctl(shm_id,IPC_RMID,NULL);

  sem_close(sem[0]);
  sem_close(sem[1]);
  sem_unlink("a");
  sem_unlink("b");

  return 0;
}
